package com.sctvcloud.renhe.ui.adapter.holder;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.AbsRunnable;
import com.ruihang.generalibrary.ui.util.IAndroidLittleLife;
import com.ruihang.generalibrary.ui.util.ViewUtils;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.renhe.R;
import com.sctvcloud.renhe.base.BaseActivity;
import com.sctvcloud.renhe.application.Constances;
import com.sctvcloud.renhe.base.BaseFragment;
import com.sctvcloud.renhe.beans.HomeLive;
import com.sctvcloud.renhe.beans.LiveItem;
import com.sctvcloud.renhe.ui.activities.LivingActivity;
import com.sctvcloud.renhe.ui.fragment.GreatestFragment;
import com.sctvcloud.renhe.ui.utils.GlideUtil;
import com.sctvcloud.renhe.ui.utils.SampleListener;
import com.sctvcloud.renhe.ui.widget.BasePlayerView;
import com.sctvcloud.renhe.ui.widget.ItemPlayerView;
import com.shuyu.gsyvideoplayer.TextureVideoViewOutlineProvider;
import com.shuyu.gsyvideoplayer.listener.INetPromt;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/7/28.
 */

public class HomeLiveHolder extends BaseAbsHolder<HomeLive> implements IAndroidLittleLife {

    private static boolean isMute = true;

    @BindView(R.id.player_main_live_video)
    protected BasePlayerView videoView;
    @BindView(R.id.living_img_video)
    protected CustomEXImageView topImg;
    @BindView(R.id.iv_live_list_item_1)
    protected CustomEXImageView img1;
    @BindView(R.id.iv_live_list_item_2)
    protected CustomEXImageView img2;
    @BindView(R.id.iv_live_list_item_3)
    protected CustomEXImageView img3;
    @BindView(R.id.ll_live_container)
    protected ViewGroup itemContain;
    @BindView(R.id.player_live_home_lay)
    protected ViewGroup videoContain;
    @BindView(R.id.iv_live_list_item_lay_2)
    protected ViewGroup item2;
    @BindView(R.id.iv_live_list_item_lay_3)
    protected ViewGroup item3;
    @BindView(R.id.tv_live_loop_title)
    protected CustomFontTextView title;

    private BaseFragment frag;
    private int lifeMode;
    private boolean hasManage;

    private HomeLive dataTemp;
    private CustomEXImageView selectTemp;

    private ImageView imageView;

    private List<CustomEXImageView> images;

    private String tempUrl;

    private Handler handler;

    private LiveItem currentItem;

    private boolean isPlaying, resuming;
    private OnLivePlayingListener playingListener;
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public HomeLiveHolder(Context context, View itemView, BaseFragment frg, OnLivePlayingListener listener) {
        super(context, itemView);
        this.frag = frg;
        this.playingListener = listener;
        handler = new Handler();
        images = new ArrayList<>();
//        ViewUtils.resetToSize(videoView, 8, 3);
        ViewUtils.resetTo169Size(videoContain);
        imageView = new ImageView(context);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setImageResource(R.mipmap.icon_def_16_9_l);
        videoView.setThumbImageView(imageView);

        if (isMute) {
            videoView.setMute(isMute);
        }
        videoView.setIsTouchWiget(false);
        videoView.setLiving(true);

        videoView.setMuteChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isMute = isChecked;
            }
        });

        videoView.setMKeepScreenOn(false);

        videoContain.setOutlineProvider(new TextureVideoViewOutlineProvider(26));
        videoContain.setClipToOutline(true);

        img1.setTag(R.id.item_news_tag, 0);
        images.add(img1);
        img2.setTag(R.id.item_news_tag, 1);
        images.add(img2);
        img3.setTag(R.id.item_news_tag, 2);
        images.add(img3);
        if (null != frag && frag instanceof GreatestFragment) {
            ((GreatestFragment) frag).initPlayer(videoView);
        }

        videoView.setNetPromt(new INetPromt() {
            @Override
            public boolean onNetPromt() {

                if (null != frag && frag instanceof GreatestFragment) {
                    ((GreatestFragment) frag).showNetDialog(videoView);
                } else {
                    videoView.startPlayLogic();
                }
                return false;
            }
        });

        videoView.setStandardVideoAllCallBack(new SampleListener() {
            @Override
            public void onPrepared(String url, Object... objects) {
                super.onPrepared(url, objects);
            }
        });
        videoView.setOnPlayerStatusListener(new BasePlayerView.OnPlayerStatusChanged() {
            @Override
            public void OnPlaying() {
                if (null != playingListener) {
                    playingListener.OnLivePaly(currentItem.getLiveId());
                }
            }

            @Override
            public void OnError() {

            }

            @Override
            public void OnStop() {

            }

            @Override
            public void OnEnd() {

            }
        });
//        JLog.e("w=" + videoView.getWidth() + "  " + img.getWidth() + "\n" + itemView.findViewWithTag(0)
//                +"\n"+itemView.findViewWithTag(0+"")
//                +"\n"+img1);
    }

    @Override
    protected void initInject() {
        ButterKnife.bind(this, itemView);
    }

    @Override
    public void setData(HomeLive homeLive) {
//        JLog.e("w=" + videoView.getWidth() + "  " + img.getWidth());
        dataTemp = homeLive;
        List<LiveItem> list = homeLive.getLiveList();
        if (!ListUtils.isListValued(list)) {
            return;
        }
        if (list.size() == 1) {
            itemContain.setVisibility(View.GONE);
            LiveItem li = list.get(0);
            setShowing(list, 0);
            setSelect(img1);
            postPlay(li.getLiveUrl());
        } else {
            itemContain.setVisibility(View.VISIBLE);
            GlideUtil.loadImgSmall169Def(context, list.get(0).getLiveImg(), img1);
            GlideUtil.loadImgSmall169Def(context, list.get(1).getLiveImg(), img2);
            if (list.size() > 2) {
                item3.setVisibility(View.VISIBLE);
                GlideUtil.loadImgSmall169Def(context, list.get(2).getLiveImg(), img3);
            } else {
                item3.setVisibility(View.GONE);
            }
            setShowing(list, homeLive.getPos());
            setSelect(images.get(homeLive.getPos()));
//            if () {
//                playerView.setPlaySource();
//                playerView.startPlay();
//            }
            postPlay(list.get(homeLive.getPos()).getLiveUrl());
        }

    }

    @Override
    public int onIResume() {
//        JLog.e("nnan resume  " + videoView);
        resuming = true;
        if (videoView != null) {
            videoView.onVideoResume();
        }
        return 0;
    }

    @Override
    public int onIPause() {
//        JLog.e("nnan pause  "+videoView);
        resuming = false;
        if (videoView != null) {
            videoView.onVideoPause();
        }
        return 0;
    }

    public void onPrepared() {
//        JLog.e("nnan pause  "+videoView);
        resuming = false;
        if (videoView != null) {
            videoView.onPrepared();
        }

    }

    @Override
    public int onIDestory() {
        JLog.e("destory  " + videoView);
        resuming = false;
        if (videoView != null) {
            videoView.onVideoPause();
            videoView.release();
        }
        return 0;
    }

    public void setLiveMute(boolean isMute) {
        if (null != videoView) {
            videoView.setMute(isMute);
        }
    }
    public boolean isResuming() {
        return resuming;
    }
    @Override
    public void setHasInManager(boolean inManager) {
        this.hasManage = inManager;
    }

    @Override
    public boolean hasInManager() {
        return hasManage;
    }

    @Override
    public void setLifeMode(int mode) {
        lifeMode = mode;
    }

    @OnClick({R.id.iv_live_list_item_1, R.id.iv_live_list_item_2, R.id.iv_live_list_item_3})
    public void itemClick(View view) {
        int pos = (int) view.getTag(R.id.item_news_tag);
        setShowing(dataTemp.getLiveList(), pos);
        dataTemp.setPos(pos);
        setSelect((CustomEXImageView) view);
        play(UrlUtils.linkUrls(Constances.ST_BASE_URL, dataTemp.getPosItem().getLiveUrl()));
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "首页"));
        pairs.add(new Pair<>("栏目", "精选"));
        pairs.add(new Pair<>("位置", "直播视频"));
        pairs.add(new Pair<>("行为类型", "点击"));
        if (activity != null) {
            GridsumWebDissector.getInstance().trackEvent(activity, "", dataTemp.getPosItem().getTitle(), "", 200, pairs);
        } else if (frag != null) {
            GridsumWebDissector.getInstance().trackEvent(frag, "", dataTemp.getPosItem().getTitle(), "", 200, pairs);
        }
    }

    @OnClick(R.id.live_title)
    public void detailClick(View view) {
        if (currentItem == null) {
            Toast.makeText(context, R.string.data_wrong, Toast.LENGTH_SHORT).show();
            return;
        }
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "首页"));
        pairs.add(new Pair<>("栏目", "精选"));
        pairs.add(new Pair<>("位置", "直播视频_详情"));
        pairs.add(new Pair<>("行为类型", "点击"));
        if (activity != null) {
            GridsumWebDissector.getInstance().trackEvent(activity, "", dataTemp.getPosItem().getTitle(), "", 200, pairs);
        } else if (frag != null) {
            GridsumWebDissector.getInstance().trackEvent(frag, "", dataTemp.getPosItem().getTitle(), "", 200, pairs);
        }
        Intent intent = new Intent(context, LivingActivity.class);
        intent.putExtra(BaseActivity.EX_URL, currentItem.getLiveContentUrl());
        intent.putExtra(BaseActivity.EX_DATA, currentItem.getLiveImg());
        context.startActivity(intent);
    }

    //    @OnClick(R.id.iv_play)
    public void playClick(View view) {
//        JLog.e("play  " + playerView + "  playing=" + isPlaying);
//        if (playerView != null) {
//            if (!isPlaying) {
//                playerView.startPlay();
//                playBtn.setEnabled(false);
//            }
//        }
    }

    private void postPlay(String url) {
        if (videoView != null && !videoView.isPlaying() && videoView.getWidth() <= 0) {
            handler.postDelayed(new AbsRunnable(url) {
                @Override
                public void run() {
                    play((String) obj);
                }
            }, 500);
        } else {
            play(url);
        }
    }

    private void setShowing(List<LiveItem> list, int pos) {
        currentItem = list.get(pos);
        title.setText(currentItem.getTitle());
    }


    /**
     * @param iv
     * @return 是否是新的选择
     */
    private boolean setSelect(CustomEXImageView iv) {
//        iv.setBackgroundResource(R.drawable.border_red);
        int pos = (int) iv.getTag(R.id.item_news_tag);
        boolean re = true;
        if (selectTemp != null) {
            if (selectTemp != iv) {
                selectTemp.setBackgroundResource(R.color.trans);
            } else {
                re = false;
            }
        }
        selectTemp = iv;
        if (dataTemp != null && ListUtils.isListValued(dataTemp.getLiveList())) {
            iv.setBackgroundResource(R.drawable.border_red);

            if (TextUtils.isEmpty(dataTemp.getLiveList().get(pos).getLiveUrl())) {
                GlideUtil.loadImgLarge169Def(context, dataTemp.getLiveList().get(pos).getLiveImg(), topImg);
                topImg.setVisibility(View.VISIBLE);
            } else {
                GlideUtil.loadImgLarge169Def(context, dataTemp.getLiveList().get(pos).getLiveImg(), imageView);
                topImg.setVisibility(View.GONE);

            }
        }
        return re;
    }

    private void play(String url) {
//        JLog.e("url=" + url + "\ntemp=" + tempUrl);
        if (TextUtils.isEmpty(url)) {
//            if (playerView != null) {
//                playerView.stopPlay();
//                img.setVisibility(View.VISIBLE);
//                playBtn.setVisibility(View.VISIBLE);
//            }
            return;
        }
//        if (!videoView.isPlaying() || !TextUtils.equals(url, tempUrl)) {
        if (videoView != null) {
            if (videoView.isPlaying()) {
                videoView.onVideoPause();
            }
//                playerView.stopPlay();
//                playerView.setLive(true);
//                playerView.setPlaySource(UrlUtils.linkUrls(Constances.ST_BASE_URL, url));
//                playerView.startPlay();
            tempUrl = url;
//                img.setVisibility(View.GONE);
//                playBtn.setVisibility(View.GONE);
            videoView.setMute(isMute);
            videoView.setUp(url, false, "");
            int net = NetModeUtil.GetNetype(context);
            if (net == 1) {
                videoView.startPlayLogic();
            } else {
//                    topImg.setVisibility(View.VISIBLE);
            }
        }
//        } else {
//            LogUtil.e("videoView.isPlaying() ==" + videoView.isPlaying() + "------TextUtils.equals(url, tempUrl) = " + TextUtils.equals(url, tempUrl));
//        }

    }

    public interface OnLivePlayingListener {
        void OnLivePaly(String liveId);
    }
}
